﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Classes;
using System.IO;
using VAdvantage.Apps;
using System.ComponentModel;
using VAdvantage.WF;
using VAdvantage.Controls;
using System.Data.SqlClient;
using System.Threading;



namespace VAdvantage.Apps.WF
{
    public partial class WFActivity : SilverlightDesktop.Controls.Form
    {
        #region Private Variables
        private int _windowNo = 0;
        private FormFrame _frame;
        /**	Open Activities				*/
        private MWFActivity[] activities = null;
        /**	Current Activity			*/
        private MWFActivity activity = null;
        /**	Current Activity			*/
        private int index = 0;
        /**	Set Column					*/
        private MColumn column = null;
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(WFActivity).FullName);

        private VComboBox vcmbForward = null;
        ToolTip tt = new ToolTip();
        #endregion
        public WFActivity()
        {

            InitializeComponent();
            SetBusy(true);
            txtBusy.Text =Msg.GetMsg("Processing");
           // vcmbForward = VAdvantage.Controls.VComboBox.CreateUser(0);
            int AD_Column_ID = 10443;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Lookup lookup = MLookupFactory.Get(Envs.GetContext(), 0,
                    AD_Column_ID, DisplayType.Search);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    vcmbForward = new VComboBox("AD_User_ID", false, false, true, lookup, 50);
                    vcmbForward.HorizontalAlignment = HorizontalAlignment.Stretch;
                    Grid.SetRow(vcmbForward, 6);
                    Grid.SetColumn(vcmbForward, 1);
                    Grid.SetColumnSpan(vcmbForward, 1);
                    LayoutRoot.Children.Add(vcmbForward);
                });
            });
            
            //tblpnlWFActivity.Controls.Add(vcmbForward, 1, 6);
            // set font of this window
            // InitialFormSetting.SetFont(this);
            // CommonFunctions.SetStatusBarProperties(stpActivity, lblStatusMsg);
        }

        //  public WFActivity()
        //   // : base(false, true, true, false, "WorkFlow Activities")
        //{
        //    InitializeComponent();
        //    vcmbForward = VAdvantage.Controls.VComboBox.CreateUser(0);
        //    tblpnlWFActivity.Controls.Add(vcmbForward, 1, 6);
        //    // set font of this window
        //    InitialFormSetting.SetFont(this);
        //    CommonFunctions.SetStatusBarProperties(stpActivity, lblStatusMsg);

        //public void Init(int WindowNo, FormFrame frame)
        //{

        //    _windowNo = WindowNo;
        //    _frame = frame;
        //    Envs.GetCtx().SetContext(_windowNo, "IsSOTrx", "Y");   //  defaults to no
        //    this.Visibility = System.Windows.Visibility.Visible;
        //    _frame.ContentGrid.Children.Add(this);

        //}


        //public void Dispose()
        //{
        //    if (_frame != null)
        //    {
        //        _frame.Dispose();
        //    }
        //    _frame = null;
        //}

        public void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }


        private void Form_Loaded(object sender, RoutedEventArgs e)
        {
            //this.Height = App.Current.Host.Content.ActualHeight - 25;
            //this.Width = App.Current.Host.Content.ActualWidth;

            DynInit(0);


            vlblAnswer.Content = Msg.GetMsg(Envs.GetContext(), "Answer");
            vlblDesc.Content = Msg.GetMsg(Envs.GetContext(), "Description", true);
            vlblForward.Content = Msg.GetMsg(Envs.GetContext(), "Forward", true);
            vlblHelp.Content = Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Help", true));
            vlblHistory.Content = Msg.GetMsg(Envs.GetContext(), "HistoryRecords", true);
            vlblNode.Content = Msg.GetMsg(Envs.GetContext(), "Node", true);
            vlblOptional.Content = "(" + Msg.GetMsg(Envs.GetContext(), "Optional", true) + ")";
            vlblTextlMsg.Content = Msg.GetMsg(Envs.GetContext(), "Messages", true);

            ibtnOk.SetValue(ToolTipService.ToolTipProperty, Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Ok", true)));
            ibtnPre.SetValue(ToolTipService.ToolTipProperty, Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Previous", true)));
            ibtnNext.SetValue(ToolTipService.ToolTipProperty, Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Next", true)));
            ibtnZoom.SetValue(ToolTipService.ToolTipProperty, Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Zoom", true)));

        }


        /// <summary>
        /// Workfolw Activity index user in alert
        /// window to open perticular index record
        /// </summary>
        public int Index
        {
            set
            {
                index = value;
            }
            get
            {
                return index;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="windowNo"></param>
        public void DynInit(int windowNo)
        {
           
            //	Forward
        //    vcmbForward = VAdvantage.Controls.VComboBox.CreateUser(windowNo);
            int AD_Column_ID = 10443;
            ThreadPool.QueueUserWorkItem(delegate
            {
                Lookup lookup = MLookupFactory.Get(Envs.GetContext(), windowNo,
                    AD_Column_ID, DisplayType.Search);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    vcmbForward = new VComboBox("AD_User_ID", false, false, true, lookup, 50);
                    vcmbForward.HorizontalAlignment = HorizontalAlignment.Left;
                    vcmbForward.Width = 190;
                    LoadActivities();
                });
            });
            
            //tblpnlWFActivity.Controls.Add(vcmbForward, 1, 6);
            //vcmbForward.Dock = DockStyle.Fill;
           
        }

        /// <summary>
        /// Load all activities to be checked
        /// </summary>
        /// <returns></returns>
        public void LoadActivities()
        {

            long start = CommonFunctions.CurrentTimeMillis();
            List<MWFActivity> list = new List<MWFActivity>();
            activities = new MWFActivity[list.Count];
            String sql = "SELECT * FROM AD_WF_Activity a "
                + "WHERE a.Processed='N' AND a.WFState='OS' AND ("
                //	Owner of Activity
                + " a.AD_User_ID=@userid"	//	#1
                //	Invoker (if no invoker = all)
                + " OR EXISTS (SELECT * FROM AD_WF_Responsible r WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID"
                + " AND COALESCE(r.AD_User_ID,0)=0 AND (a.AD_User_ID=@userid OR a.AD_User_ID IS NULL))"	//	#2
                // Responsible User
                + " OR EXISTS (SELECT * FROM AD_WF_Responsible r WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID"
                + " AND r.AD_User_ID=@userid)"		//	#3
                //	Responsible Role
                + " OR EXISTS (SELECT * FROM AD_WF_Responsible r INNER JOIN AD_User_Roles ur ON (r.AD_Role_ID=ur.AD_Role_ID)"
                + " WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID AND ur.AD_User_ID=@userid)"	//	#4
                //
                + ") ORDER BY a.Priority DESC, Created";
            int AD_User_ID = Envs.GetContext().GetAD_User_ID();
            try
            {
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@userid", AD_User_ID);

                ThreadPool.QueueUserWorkItem(delegate
                {
                    DataSet ds = DB.ExecuteDataset(sql, param);

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        list.Add(new MWFActivity(Envs.GetContext(), dr, null));
                        if (list.Count > 200)		//	HARDCODED
                        {
                            log.Warning("More than 200 Activities - ignored");
                            break;
                        }
                    }
                    activities = new MWFActivity[list.Count];
                    activities = list.ToArray();
                    log.Fine("#" + activities.Length + "(" + (CommonFunctions.CurrentTimeMillis() - start) + "ms)");
                    Dispatcher.BeginInvoke(() => Display());

                });


            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
            }


            //
            //   log.Fine("#" + activities.Length + "(" + (CommonFunctions.CurrentTimeMillis() - start) + "ms)");
            // index = 0;//This is comment for Grid Zoom Action
            //return activities.Length;
        }


        /// <summary>
        /// Display one activity at a time
        /// </summary>
        public void Display()
        {
            String nodes, help, discription, webHstory;

            log.Fine("Index=" + index);
            //
            vtxtTextMsg.Text = "";

            vtxtAnswer.Visibility = Visibility.Collapsed;
            vcmbAnswer.Visibility = Visibility.Collapsed;
            vbtnAnswer.Visibility = Visibility.Collapsed;
            //vbtnAnswer.Image = Properties.Resources.mProcess; //mWindow.gif

            vtxtTextMsg.IsReadOnly = activities.Length == 0;
            ibtnZoom.IsEnabled = activities.Length != 0;
            ibtnOk.IsEnabled = activities.Length != 0;
            vcmbForward.SetValue(null);
            vcmbForward.IsEnabled = activities.Length != 0;
            //    CommonFunctions.ShowMessage(index + "/" + activities.Length, lblStatusRecord);
            activity = null;
            if (activities.Length > 0)
            {
                if (index + 1 > activities.Length)
                {
                    log.Log(Level.SEVERE, "Index (" + index + ") greater then activity length=" + activities.Length);
                    index = 0;
                }
                //else
                //    activity = activities[index];
                try
                {
                    activity = activities[index];
                }
                catch
                {
                    activity = null;
                }
            }
            //	Nothing to show
            if (activity == null)
            {
                vtxtNode.Text = "";
                vtxtDescription.Text = "";
                vtxtHelp.Text = "";
                wbHistory.Html = "";
                CommonFunctions.ShowMessage(Msg.GetMsg(Envs.GetContext(), "WFNoActivities", true), lblStatusMsg);
                //    CommonFunctions.ShowMessage("0/0", lblStatusRecord);
                ibtnNext.IsEnabled = false;
                ibtnPre.IsEnabled = false;
                SetBusy(false);
                return;
            }
            //	Display Activity



            ThreadPool.QueueUserWorkItem(delegate
            {
                nodes = activity.GetNodeName();
                discription = activity.GetNodeDescription();
                help = activity.GetNodeHelp();
                webHstory = activity.GetHistoryHTML();

                Dispatcher.BeginInvoke(delegate
                {
                    vtxtNode.Text = Util.GetValueOfString(nodes);
                    vtxtDescription.Text = Util.GetValueOfString(discription);
                    vtxtHelp.Text = Util.GetValueOfString(help);
                    wbHistory.Html = webHstory;
                });


                //	User Actions
                MWFNode node = activity.GetNode();
                if (MWFNode.ACTION_UserChoice.Equals(node.GetAction()))
                {
                    if (column == null)
                        column = node.GetColumn();
                    if (column != null && column.Get_ID() != 0)
                    {
                        int dt = column.GetAD_Reference_ID();
                        if (dt == DisplayType.YesNo)
                        {
                            ValueNamePair[] values = MRefList.GetList(319, false);		//	_YesNo
                            Dispatcher.BeginInvoke(delegate
                            {
                                vcmbAnswer.ItemsSource = values;
                                vcmbAnswer.Visibility = Visibility.Visible;
                                SetWidth(vcmbAnswer);
                                SetBusy(false);
                            });
                        }
                        else if (dt == DisplayType.List)
                        {
                            ValueNamePair[] values = MRefList.GetList(column.GetAD_Reference_Value_ID(), false);
                            Dispatcher.BeginInvoke(delegate
                            {
                                vcmbAnswer.ItemsSource = values;
                                vcmbAnswer.Visibility = Visibility.Visible;
                                SetWidth(vcmbAnswer);
                                SetBusy(false);
                            });
                        }
                        else	//	other display types come here
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                vtxtAnswer.Text = "";
                                vtxtAnswer.Visibility = Visibility.Visible;
                                SetBusy(false);
                            });
                        }
                    }
                }
                //	--
                else if (MWFNode.ACTION_UserWindow.Equals(node.GetAction())
                    || MWFNode.ACTION_UserForm.Equals(node.GetAction()))
                {
                    Dispatcher.BeginInvoke(delegate
                            {
                                vbtnAnswer.Content = node.GetName();
                                //tt.SetToolTip(vbtnAnswer, node.GetDescription());
                                vbtnAnswer.SetValue(ToolTipService.ToolTipProperty, Util.CleanMnemonic(Msg.GetMsg(Envs.GetContext(), "Ok", true)));
                                vbtnAnswer.Visibility = Visibility.Visible;
                                SetBusy(false);
                            });
                }
                else if (MWFNode.ACTION_UserWorkbench.Equals(node.GetAction()))
                {
                    log.Log(Level.SEVERE, "Workflow Action not implemented yet");
                    Dispatcher.BeginInvoke(delegate
                           {
                               SetBusy(false);
                           });
                }
                else
                {
                    log.Log(Level.SEVERE, "Unknown Node Action: " + node.GetAction());
                    Dispatcher.BeginInvoke(delegate
                           {
                               SetBusy(false);
                           });
                }
            });
            //
            //if (m_menu != null)
            //{
            //    m_menu.updateInfo();	//	calls loadActivities - updates menu tab
            //}
            //	End
            if (index + 1 >= activities.Length)
            {
                index = activities.Length - 1;
                ibtnNext.IsEnabled = false;
            }
            else
                ibtnNext.IsEnabled = true;
            //	Start
            if (index <= 0)
            {
                index = 0;
                ibtnPre.IsEnabled = false;
            }
            else
                ibtnPre.IsEnabled = true;
            CommonFunctions.ShowMessage(Msg.GetMsg(Envs.GetContext(), "WFActivities", true), lblStatusMsg);
            //  CommonFunctions.ShowMessage((index + 1) + "/" + activities.Length, lblStatusRecord);

        }


        private void SetWidth(Control ctrl)
        {
            ctrl.Width = 185;
        }

        private void ibtnPre_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            index--;
            Display();
        }

        private void ibtnNext_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            index++;
            Display();
        }

        private void ibtnZoom_Click(object sender, RoutedEventArgs e)
        {
            log.Config("Activity=" + activity);
            if (activity == null)
            {
                SetBusy(false);
                return;
            }
            AEnv.Zoom(activity.GetAD_Table_ID(), activity.GetRecord_ID());
        }

        private void ibtnOk_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            log.Config("Activity=" + activity);
            if (activity == null)
            {
                SetBusy(false);
                return;
            }
            int AD_User_ID = Envs.GetContext().GetAD_User_ID();
            String textMsg = vtxtTextMsg.Text.Trim();
            Object forward = vcmbForward.GetValue();
            ValueNamePair pp = (ValueNamePair)vcmbAnswer.SelectedItem;

            if (forward != null)
            {
                log.Config("Forward to " + forward);
                int fw = int.Parse(forward.ToString());
                if (fw == AD_User_ID || fw == 0)
                {
                    SetBusy(false);
                    log.Log(Level.SEVERE, "Forward User=" + fw);
                    return;
                }
                if (!activity.ForwardTo(fw, textMsg))
                {
                    SetBusy(false);
                    ShowMessage.Error("CannotForward", true);
                    return;

                }
            }
            //
            ThreadPool.QueueUserWorkItem(delegate
            {
                MWFNode node = activity.GetNode();



                //	User Choice - Answer
                if (MWFNode.ACTION_UserChoice.Equals(node.GetAction()))
                {
                    if (column == null)
                        column = node.GetColumn();
                    //	Do we have an answer?
                    int dt = column.GetAD_Reference_ID();
                    String value = null;
                    if (dt == DisplayType.YesNo || dt == DisplayType.List)
                    {

                        //  value = vtxtAnswer.Text.Trim();
                        value = pp.GetValue();
                        if (value == null || value.Length == 0)
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                SetBusy(false);
                                ShowMessage.Error("FillMandatory", true, Msg.GetMsg(Envs.GetContext(), "Answer", true));
                                log.Config("Answer=" + value + " - " + textMsg);
                                return;
                            });
                            return;
                        }
                        //

                    }

                    try
                    {
                        activity.SetUserChoice(AD_User_ID, value, dt, textMsg);
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.BeginInvoke(delegate
                                {
                                    SetBusy(false);
                                    log.Log(Level.SEVERE, node.GetName(), ex);
                                    ShowMessage.Error("Error", true, ex.ToString());
                                    return;
                                });
                        return;
                    }
                }
                //	User Action
                else
                {
                    log.Config("Action=" + node.GetAction() + " - " + textMsg);
                    try
                    {
                        activity.SetUserConfirmation(AD_User_ID, textMsg);
                    }
                    catch (Exception exx)
                    {
                        Dispatcher.BeginInvoke(delegate
                                {
                                    SetBusy(false);
                                    log.Log(Level.SEVERE, node.GetName(), exx);
                                    ShowMessage.Error("Error", true, exx.ToString());
                                    return;
                                });
                        return;
                    }

                }

                //	Next
                Dispatcher.BeginInvoke(() => LoadActivities());


            });

        }

        private void vbtnAnswer_Click(object sender, RoutedEventArgs e)
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            log.Config("Activity=" + activity);
            if (activity == null)
            {
                SetBusy(false);
                return;
            }
            //
            ThreadPool.QueueUserWorkItem(delegate
            {
                MWFNode node = activity.GetNode();
                if (MWFNode.ACTION_UserWindow.Equals(node.GetAction()))
                {
                    int AD_Window_ID = node.GetAD_Window_ID();		// Explicit Window
                    String ColumnName = activity.GetPO().Get_TableName() + "_ID";
                    int Record_ID = activity.GetRecord_ID();
                    Query query = Query.GetEqualQuery(ColumnName, Record_ID);
                    bool IsSOTrx = activity.IsSOTrx();
                    //
                    log.Info("Zoom to AD_Window_ID=" + AD_Window_ID + " - " + query + " (IsSOTrx=" + IsSOTrx + ")");
                    Dispatcher.BeginInvoke(delegate
                    {
                        AWindow frame = new AWindow();
                        // get window
                        //Framework.VForm obj = frame.InitilizeWindow(query, false, AD_Window_ID);
                        if (frame.InitWindow(AD_Window_ID, query))
                        {
                            SetBusy(false);
                            // show the window
                            // frame.StartPosition = FormStartPosition.CenterScreen;
                            //frame.Show();
                        }
                        frame = null;
                    });
                }
                else if (MWFNode.ACTION_UserForm.Equals(node.GetAction()))
                {
                    int AD_Form_ID = node.GetAD_Form_ID();
                    Dispatcher.BeginInvoke(delegate
                                        {
                                            SetBusy(false);
                                        });
                }
                else if (MWFNode.ACTION_UserWorkbench.Equals(node.GetAction()))
                {

                }
                else
                {
                    log.Log(Level.SEVERE, "No User Action:" + node.GetAction());
                }
            });
        }

        private void vtxtNode_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void vtxtHelp_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void vtxtDescription_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

    }
}

